﻿@page "/counter"
@* @rendermode @(new InteractiveAutoRenderMode(prerender: false)) *@
@rendermode InteractiveAuto
@inject Csla.Blazor.State.StateManager StateManager
@inject ApplicationContext applicationContext

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

@if (IsInteractive)
{
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
}

@code {
    [CascadingParameter]
    private Task<AuthenticationState>? authenticationState { get; set; }
    private int currentCount = 0;
    private bool IsInteractive;

    protected override async Task OnInitializedAsync()
    {
        // Every page _must_ initialize the state manager
        await StateManager.InitializeAsync();
        if (applicationContext.LocalContext.Contains("counter"))
        {
            var value = applicationContext.LocalContext["counter"];
            currentCount = value == null ? 0 : (int)value;
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            IsInteractive = true;
            StateHasChanged();
        }
    }

    private void IncrementCount()
    {
        currentCount++;
        applicationContext.LocalContext["counter"] = currentCount;
    }
}
